<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017 Tangchao All rights reserved.
// +----------------------------------------------------------------------
// | Author: xiaoying <360963804@qq.com>
// +----------------------------------------------------------------------
namespace plugins\ali_pay\controller;

use cmf\controller\PluginBaseController;
use think\Db;
// use app\user\model\UserModel;
// use think\Exception;

class IndexController extends PluginBaseController
{

    //扫码付
    public function qrcode()
    {
		global $orderParameter;
		
        //充值金额
        $money = $orderParameter['total_fee'];

        require __DIR__ . '/../lib/f2fpay/service/AlipayTradeService.php'; //引入支付宝当面付
        require __DIR__ . '/../lib/f2fpay/model/builder/AlipayTradePayContentBuilder.php'; //引入支付宝当面付
        $out_trade_no = $orderParameter['out_trade_no'];
        $payRequestBuilder = new \AlipayTradePayContentBuilder();
        $payRequestBuilder->setBody('扫码支付' . $money . '元');
        $payRequestBuilder->setSubject('扫码支付' . $money . '元');
        $payRequestBuilder->setTotalAmount($money);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $result = new \AlipayTradeService(cmf_get_plugin_config("AliPay"));
        $result = $result->qrPay($payRequestBuilder);

        if ($result->getTradeStatus() == "SUCCESS") {
            $response = $result->getResponse();
            return [
                'code' => 1,
                'url' => $response->qr_code,
                'out_trade_no' => $out_trade_no,
            ];
        } else {
            $response = $result->getResponse();
            return ['code' => 0, 'msg' => $response->sub_msg];
        }
    }

    //H5支付
    public function h5()
    {
		global $orderParameter;
		
        //充值金额
        $money = $orderParameter['total_fee'];

        require __DIR__ . '/../lib/aop/AopClient.php';
        require __DIR__ . '/../lib/aop/request/AlipayTradeWapPayRequest.php'; //引入h5支付
        $body         = 'H5支付' . $money . '元';
        $subject      = 'H5支付' . $money . '元';
        $out_trade_no = $orderParameter['out_trade_no'];  //随机字符串，订单号，回调使用
        $aliConfig = cmf_get_plugin_config("AliPay");
        $aop = new \AopClient();
        $aop->gatewayUrl = $aliConfig['gatewayUrl'];
        $aop->appId = $aliConfig['app_id'];
        $aop->rsaPrivateKey = $aliConfig['merchant_private_key'];
        $aop->alipayrsaPublicKey = $aliConfig['alipay_public_key'];
        $aop->apiVersion = '1.0';
        $aop->postCharset = $aliConfig['charset'];
        $aop->format = 'json';
        $aop->signType = $aliConfig['sign_type'];
        $request = new \AlipayTradeWapPayRequest();
        $bizContent = "{" .
            "    \"body\":\"$body.\"," .
            "    \"subject\":\"$subject\"," .
            "    \"out_trade_no\":\"$out_trade_no\"," .
            "    \"timeout_express\":\"90m\"," .
            "    \"total_amount\":$money," .
            "    \"product_code\":\"QUICK_WAP_WAY\"" .
            "  }";
        $request->setBizContent($bizContent);
        $request->setNotifyUrl($aliConfig['notify_url']);
        $request->setReturnUrl($aliConfig['return_url']);
        $result = $aop->pageExecute($request);

        echo $result;


    }



    //轮询订单
    public function payFind()
    {
        //商家订单号
        $out_trade_no = $this->request->param('out_trade_no');

        $status = DB::name('portal_post_order')
            ->where('post_title', $out_trade_no) //商户自定义订单号
            ->value('orderstatus');

        if ($status == 1) {
            $this->success("支付成功");
        } else {
            $this->error('支付失败');
        }
    }


    /**
     * 阿里云当面付支付回调处理
     */
    //     2020-01-27 14:57:25:Array
    // (
    //     [s] => xxxxx
    //     [gmt_create] => 2020-01-27 14:57:13
    //     [charset] => UTF-8
    //     [seller_email] => xxxxx
    //     [subject] => 扫码支付0.01元
    //     [sign] => xxxxx
    //     [body] => tset
    //     [buyer_id] => xxxx
    //     [invoice_amount] => 0.01
    //     [notify_id] => xxxxx
    //     [fund_bill_list] => [{"amount":"0.01","fundChannel":"ALIPAYACCOUNT"}]
    //     [notify_type] => trade_status_sync
    //     [trade_status] => TRADE_SUCCESS
    //     [receipt_amount] => 0.01
    //     [buyer_pay_amount] => 0.01
    //     [app_id] => XXXXX
    //     [sign_type] => RSA2
    //     [seller_id] => xxxx
    //     [gmt_payment] => 2020-01-27 14:57:24
    //     [notify_time] => 2020-01-27 14:57:25
    //     [version] => 1.0
    //     [out_trade_no] => xxxxx
    //     [total_amount] => 0.01
    //     [trade_no] => xxxx
    //     [auth_app_id] => XXXXX
    //     [buyer_logon_id] => xxxxx
    //     [point_amount] => 0.00
    // )
    public function callback()
    {
        // import('alipay.aop.AopClient');
        // cmh_log('pay', print_r($_REQUEST, true));
        require __DIR__ . '/../lib/aop/AopClient.php'; //引入支付宝当面付
        $config = cmf_get_plugin_config("AliPay");
        $out_trade_no = input('post.out_trade_no');
        $transaction_id = input('post.trade_no');
        $aop = new \AopClient;
        $aop->appId = $config['app_id'];
        $aop->rsaPrivateKey = $config['merchant_private_key'];
        $aop->alipayrsaPublicKey = $config['alipay_public_key'];
        $aop->signType = $config['sign_type'];
        $result = $aop->rsaCheckV1($_POST, '', $config['sign_type']);
        if ($result) {
            if (input('trade_status') == 'TRADE_FINISHED' || input('trade_status') == 'TRADE_SUCCESS') {
                // 处理支付成功后的逻辑业务
                $order =  DB::name('portal_post_order')->where(['out_trade_no' => $out_trade_no])->find();
                if (!$order) {
                    return 'order not exists';
                }
                //订单状态错误 0 未付款 其他状态均为已处理的状态
                if ($order['orderstatus'] != 0) {
                    return true;
                }
				
				// 付款成功后会员帐户操作
				setMemberPayOpeater($order['id']);
				
                //改变订单状态
                DB::name('portal_post_order')
                    ->where('post_title', $out_trade_no) //商户自定义订单号
                    ->update([
                        'status'         => 1,                 //已支付
                        'update_time'       => time()             //完成时间
                    ]);
					
                //支付成功的逻辑
                return 'success';
            }
            return 'fail';
        }
        return 'fail';
    }
}
